package _18_剑指OfferII;

public class _002_剑指OfferII二进制加法 {

    public static void main(String[] args) {


        _002_剑指OfferII二进制加法 v = new _002_剑指OfferII二进制加法();

        String str1 = "100";
        String str2 = "110010";
        System.out.println(v.addBinary(str1, str2));

    }

    public String addBinary(String a, String b) {
        StringBuilder sb = new StringBuilder();
        int carry = 0;
        int aEnd = a.length() - 1;
        int bEnd = b.length() - 1;
        int end = Math.max(aEnd, bEnd);
        for (int i = 0; i <= end; i++) {
            carry += aEnd - i >= 0? a.charAt(aEnd - i) - '0': 0;
            carry += bEnd - i >= 0? b.charAt(bEnd - i) - '0': 0;
            sb.append((char)(carry % 2 + '0'));
            carry >>= 1;
        }
        if (carry > 0) {
            sb.append('1');
        }
        return sb.reverse().toString();
    }

}
